<template>
  <div class="model-main">
    <div class="model-title">
      <span style="font-size: 23px;margin: 20px 0">健康生活，健康人生，从此刻开始!</span>
      <h1>
        每一点改变都值得被记录!
        <el-button type="info" size="large" style="background-color: black" @click="toRecord">
          <span style="font-size: 20px;font-weight: bold">前去记录 →</span>
        </el-button>
      </h1>
    </div>
    <!--图表部分-->
    <div class="chart">
      <ModelChart :key="chartReload"></ModelChart>
    </div>
    <!--    表格部分-->
    <div class="model-data">
      <h2 style="border-left: #4284db 3px solid;padding-left: 10px">
        健康指标数据
        <el-button type="primary" size="default" style="float: right" @click="openAiDialog">AI分析模型</el-button>
      </h2>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-icon style="margin: 2px 10px 0 0" v-if="scope.row.status=='正常'"><CircleCheckFilled style="color: green"/></el-icon>
            <el-icon style="margin: 2px 10px 0 0" v-else><WarningFilled style="color: red;" /></el-icon>
            <el-icon></el-icon>
            <span>{{ scope.row.status}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="value" label="值" />
        <el-table-column prop="healthModel.name" label="模型名" sortable/>
        <el-table-column prop="healthModel.unit" label="单位" />
        <el-table-column prop="healthModel.unitCn" label="中文单位"/>
        <el-table-column label="正常范围" >
          <template #default="scope">
            <span>{{ scope.row.healthModel.minValue }}~{{ scope.row.healthModel.maxValue }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="记录时间"  sortable>
          <template #default="scope">
            {{ parseTime(scope.row.createTime, '{y}年{m}月{d}日') }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <span class="deleteRecord" @click="deleteModelRecord(scope.row.id)">删除</span>
          </template>
        </el-table-column>
      </el-table>
    </div>


    <el-dialog v-model="aiDialog" title="AI分析模型" width="900" >
      <div v-if="aiChatLoading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      <div v-else class="ai-response" v-html="aiChat"></div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="aiDialog = false">取消</el-button>
          <el-button type="primary" @click="aiDialog = false">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import router from "@/router/index.js";
import {onMounted, ref} from "vue";
import ModelChart from "@/components/Echart/ModelChart.vue";
import {deleteModelRecordApi, getModelNameChartApi, getModelRecordApi} from "@/api/model.js";
import {parseTime} from "../../tool/utils.js";
import {ElMessage} from "element-plus";
import {loginAuth} from "@/tool/commonFun.js";
import {CircleCheckFilled} from "@element-plus/icons-vue";


//表格数据
const tableData = ref(null)
//图表重新加载
const chartReload = ref(true)
const aiDialog = ref(false)
const selectModels = ref([])
const aiChat = ref('')
const aiChatLoading = ref(true) // 保持初始为true

onMounted(() => {
  initData()
})

function initData() {
  if (loginAuth() == 0) {
    return
  }
  getRecord()
}

function getRecord() {
  getModelRecordApi().then(res => {
    tableData.value = res.data
  })
}

function deleteModelRecord(id) {
  deleteModelRecordApi(id).then(res => {
    ElMessage({message: res.msg, type: 'success'})
    getRecord()
    chartReload.value = !chartReload.value
  })
}

const openAiDialog = async () => {
  // ElMessage({message:'此功能正在开发中',type:"error"})
  aiChat.value = ''
  aiDialog.value = true
  aiChatLoading.value = true // 打开对话框时开始加载

  const response = await fetch('/api/ai', {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': localStorage.getItem('token')
    },
  })

  if (!response.ok) throw new Error('请求失败')
  if (!response.body) throw new Error('无响应体')

  const reader = response.body.getReader()
  const decoder = new TextDecoder('utf-8')
  aiChatLoading.value = false // 开始接收数据时关闭加载

  while (true) {
    const {done, value} = await reader.read()
    if (done) break

    // 处理流数据
    const chunk = decoder.decode(value)
    const jsonStr = chunk.replace(/data:/g, '').trim()
    console.log(chunk.trim() + '-----------' + jsonStr.trim())
    // console.log(data.result.output.content)
  
    aiChat.value += jsonStr.trim()
  }
}
//跳转去记录
function toRecord() {
  router.push('/health/record')
}
</script>

<style scoped>
.model-main {
  display: flex;
  align-items: center;
  flex-direction: column;
}

.model-title {
  width: 80%;
  display: flex;
  align-items: center;
  flex-direction: column;
  background-color: #F9F9F9;
  border-radius: 7px;
}

.model-data {
  width: 80%
}

.deleteRecord:hover {
  cursor: pointer;
}
.chart{
  width: 80%;
}
.ai-response ::v-deep think {
  color: #666;
  background-color: #f5f5f5;
  display: block;
  padding: 10px;
  margin: 10px 0;
  border-radius: 4px;
  font-style: italic;
}
.ai-response ::v-deep div {
  color: #333;
}
.loading-container {
  padding: 20px;
  min-height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>